import 'dart:convert';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:merchants/models/attr_name.dart';
import 'package:merchants/services/base-service.dart';

class AttrNameService extends BaseService {
  AttrNameService({required super.ref});

  Future<List<AttrName>> getList() async {
    final response = await get<Map<String, dynamic>>(
      '/admin/attr-name/get-list',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '获取规格名称列表失败');
        }
        return json;
      },
    );
    final List<dynamic> records = response['data'] as List<dynamic>;
    return records
        .map((json) => AttrName.fromJson(json as Map<String, dynamic>))
        .toList();
  }

  // 新增规格名称
  Future<AttrName> createAttrName(String attrName) async {
    final response = await post<Map<String, dynamic>>(
      '/admin/attr-name/create',
      body: {'name': attrName},
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '创建规格名称失败');
        }
        return json;
      },
    );
    final id = response['data']['id'] as String;
    return AttrName(id: id, name: attrName);
  }

  // 更新规格名称
  Future<AttrName> updateAttrName(
    String id,
    String attrName,
  ) async {
    await put<Map<String, dynamic>>(
      '/admin/attr-name/$id',
      body: {'name': attrName},
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '更新规格名称失败');
        }
        return json;
      },
    );
    return AttrName(id: id, name: attrName);
  }

  Future<void> deleteAttrName(String? id) async {
    await delete<void>(
      '/admin/attr-name/$id',
      parser: (json) {
        if (json['success'] != true) {
          throw ApiException(json['message'] ?? '删除规格名称失败');
        }
      },
    );
  }


}
